'use client';

import { useEffect, useState } from 'react';
import Link from 'next/link';
import { notFound, useParams } from 'next/navigation';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Receipt, Building2, ArrowLeft, Pencil, Trash2 } from 'lucide-react';
import { formatMoney, formatDate, getApiUrl } from '@/lib/utils';

const expenseTypeMap = {
  material: '材料费',
  labor: '人工费',
  equipment: '设备费',
  other: '其他费用'
} as const;

type ExpenseType = keyof typeof expenseTypeMap;

interface Expense {
  id: string;
  siteId: string;
  type: ExpenseType;
  amount: number;
  paymentDate: string;
  vendor: string | null;
  description: string | null;
  site: {
    id: string;
    name: string;
  };
}

function ExpenseDetails({ expense }: { expense: Expense }) {
  return (
    <div className="space-y-6">
      <div className="flex flex-col gap-4 md:flex-row md:items-start md:justify-between">
        <div>
          <h1 className="text-3xl font-bold tracking-tight">支出详情</h1>
          <p className="text-muted-foreground">
            支付时间：{formatDate(expense.paymentDate)}
          </p>
        </div>
        <div className="flex gap-2">
          <Button asChild>
            <Link href={`/expenses/${expense.id}/edit`}>
              <Pencil className="mr-2 h-4 w-4" />
              编辑支出
            </Link>
          </Button>
          <Button variant="destructive" asChild>
            <Link href={`/expenses/${expense.id}/delete`}>
              <Trash2 className="mr-2 h-4 w-4" />
              删除支出
            </Link>
          </Button>
        </div>
      </div>

      <div className="grid gap-4 md:grid-cols-2">
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">支出金额</CardTitle>
            <Receipt className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{formatMoney(expense.amount)}</div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">所属工地</CardTitle>
            <Building2 className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <Link 
              href={`/sites/${expense.siteId}`}
              className="text-2xl font-bold hover:underline"
            >
              {expense.site.name}
            </Link>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">支出类型</CardTitle>
            <Receipt className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{expenseTypeMap[expense.type]}</div>
          </CardContent>
        </Card>

        {expense.vendor && (
          <Card>
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <CardTitle className="text-sm font-medium">供应商</CardTitle>
              <Building2 className="h-4 w-4 text-muted-foreground" />
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">{expense.vendor}</div>
            </CardContent>
          </Card>
        )}

        {expense.description && (
          <Card className="md:col-span-2">
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <CardTitle className="text-sm font-medium">备注说明</CardTitle>
              <Receipt className="h-4 w-4 text-muted-foreground" />
            </CardHeader>
            <CardContent>
              <p className="text-lg whitespace-pre-wrap">{expense.description}</p>
            </CardContent>
          </Card>
        )}
      </div>
    </div>
  );
}

export default function ExpensePage() {
  const params = useParams();
  const id = params.id as string;
  const [expense, setExpense] = useState<Expense | null>(null);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    async function loadExpense() {
      try {
        const response = await fetch(getApiUrl(`expenses/${id}`));
        if (!response.ok) {
          if (response.status === 404) {
            notFound();
          }
          throw new Error('加载支出详情失败');
        }
        const data = await response.json();
        setExpense(data);
      } catch (error) {
        console.error('加载支出详情失败:', error);
      } finally {
        setIsLoading(false);
      }
    }
    loadExpense();
  }, [id]);

  if (isLoading) {
    return (
      <main className="container mx-auto p-4 space-y-4">
        <Button variant="ghost" asChild className="mb-4">
          <Link href="/expenses">
            <ArrowLeft className="mr-2 h-4 w-4" />
            返回支出列表
          </Link>
        </Button>
        <div>加载中...</div>
      </main>
    );
  }

  if (!expense) {
    return (
      <main className="container mx-auto p-4 space-y-4">
        <Button variant="ghost" asChild className="mb-4">
          <Link href="/expenses">
            <ArrowLeft className="mr-2 h-4 w-4" />
            返回支出列表
          </Link>
        </Button>
        <div>支出记录不存在</div>
      </main>
    );
  }

  return (
    <main className="container mx-auto p-4 space-y-4">
      <Button variant="ghost" asChild className="mb-4">
        <Link href="/expenses">
          <ArrowLeft className="mr-2 h-4 w-4" />
          返回支出列表
        </Link>
      </Button>

      <ExpenseDetails expense={expense} />
    </main>
  );
} 